<?php

namespace app\common\logic;

use app\api\validate\FollowUpValidate;
use app\common\basic\BaseLogic;
use app\common\model\CrmCustomerMetas;
use app\common\model\CrmCustomers;
use app\common\model\CrmFollowUps;
use app\common\model\SystemUser;
use think\facade\Db;
use Webman\Event\Event;

class FollowUpLogic extends BaseLogic
{
    protected $model;
    protected $validate;

    public function __construct()
    {
        $this->model = new CrmFollowUps();
        $this->validate = new FollowUpValidate();
    }

    /**
     * 创建跟进记录
     * @param array $data 跟进数据
     * @param int $userId 当前用户ID
     * @return array
     * @throws \Exception
     */
    public function createFollowUp(array $data, int $userId): bool
    {
        // 验证数据
        if (!$this->validate->scene('create')->check($data)) {
            throw new \Exception($this->validate->getError());
        }

        // 设置跟进人
        $data['user_id'] = $userId;

        // 处理图片数据
        if (!empty($data['images'])) {
            if (is_string($data['images'])) {
                $data['images'] = explode(',', $data['images']);
            }
        }
        $data['images'] = json_encode($data['images'] ?? []);

        // 处理跟进时间
        if (empty($data['followup_time'])) {
            $data['followup_time'] = date('Y-m-d H:i:s');
        }
        // 创建跟进记录
        try {
            $this->model->transaction(function () use ($data) {
                $this->model->save($data);
                
                $customer = CrmCustomers::findOrEmpty($data['customer_id']);
                $baseData = $customer->toArray();
                if (!$customer->isEmpty() && $customer->stage == 1) {
                    $customer->stage = 2;
                }
                $customer->follow_up_count = Db::raw('follow_up_count+1');
                $customer->follow_up_time = empty($data['followup_time']) ? date('Y-m-d H:i:s') : $data['followup_time'];
                $customer->save();
                
                Event::emit('customer.changed', [
                    'customerId' => $customer->id,
                    'eventType' => '新增跟进',
                    'originalCustomerData' => $baseData,
                    'newCustomerData' => $customer->toArray(),
                ]);
            });
        } catch (\Exception $e) {
            return false;
        }
        return true;
    }

    /**
     * 获取跟进列表
     * @param array $params 查询参数
     * @param int $userId 当前用户ID
     * @return array
     */
    public function getFollowUpList(array $params, int $userId): array
    {
        $where = [];
        // 按客户筛选
        if (!empty($params['customer_id'])) {
            $where['customer_id'] = $params['customer_id'];
        }

        // 按跟进人筛选
        if (!empty($params['user_id'])) {
            $where['user_id'] = $params['user_id'];
        }
        // 按跟进方式筛选
        if (!empty($params['type'])) {
            $where['type'] = $params['type'];
        }

        if (!empty($userId)) {
            $where['user_id'] = $userId;
        }

        if (!empty($params['name'])) {
            $params['name'] = trim(strip_tags($params['name']));
        }

        $query = $this->search($where)->alias('f')->when(!empty($params['name']), function ($query) use ($params) {
           $subQuery = CrmCustomers::alias('c')
               ->leftJoin(CrmCustomerMetas::getTable().' m', 'c.id = m.customer_id')
               ->where('m.delete_time', null)
               ->whereIn('m.meta_key', ['contact_name', 'contact_person'])
               ->whereLike('m.meta_value', "%{$params['name']}%")
               ->where('c.delete_time', null)
               ->whereRaw('f.customer_id = c.id')->buildSql(true);
           
            $subQuery2 = SystemUser::alias('u')->where('u.nickname', 'like', "%{$params['name']}%")->where('f.user_id', Db::raw('u.id'))->buildSql(true);
            
            $query->where(function($query) use ($subQuery, $subQuery2) {
                $query->whereExists($subQuery)->whereOr(function($query) use ($subQuery2) {
                    $query->whereExists($subQuery2);
                });
            });
        })->with(['customer', 'user', 'partner']);
        // 按时间范围筛选
        if (!empty($params['create_time'])) {
            $query->whereTime('create_time', 'between', parseDateRange($params['create_time'], ',', true, 'Y-m-d H:i:s'));
        }

        // 分页
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $list = $query->order('create_time', 'desc')->paginate(['list_rows' => $limit, 'page' => $page]);

        return $list->toArray();
    }

    /**
     * 获取跟进详情
     * @param int $id 跟进ID
     * @param int $userId 当前用户ID
     * @return array
     * @throws \Exception
     */
    public function getFollowUpDetail(int $id, int $userId): array
    {
        $followUp = $this->model->with(['customer', 'user', 'partner'])
            ->where('id', $id)
            ->where('delete_time', null)
            ->find();

        if (!$followUp) {
            throw new \Exception('跟进记录不存在');
        }

        // 处理图片数据
        if (!empty($followUp->images)) {
            $followUp->images = json_decode($followUp->images, true);
        }

        return $followUp->toArray();
    }

    /**
     * 删除跟进记录（软删除）
     * @param int $id 跟进ID
     * @param int $userId 当前用户ID
     * @return bool
     * @throws \Exception
     */
    public function deleteFollowUp(int $id, int $userId): bool
    {
        $followUp = $this->model->where('id', $id)
            ->where('delete_time', null)
            ->find();

        if (!$followUp) {
            throw new \Exception('跟进记录不存在');
        }

        // 检查权限：只能删除自己创建的跟进记录
        if ($followUp->user_id != $userId) {
            throw new \Exception('无权限删除他人的跟进记录');
        }

        return $followUp->save(['delete_time' => date('Y-m-d H:i:s')]);
    }

    /**
     * 验证跟进数据
     * @param array $data
     * @throws \Exception
     */
    protected function validateFollowUpData(array $data): void
    {
        // 验证客户ID
        if (empty($data['customer_id'])) {
            throw new \Exception('客户ID不能为空');
        }

        // 验证跟进方式
        if (!isset($data['type']) || !in_array($data['type'], [1, 2])) {
            throw new \Exception('跟进方式不能为空，必须是1(实地)或2(电话)');
        }

        // 验证跟进纪要
        if (empty($data['content'])) {
            throw new \Exception('跟进纪要不能为空');
        }

        if (strlen($data['content']) > 500) {
            throw new \Exception('跟进纪要不能超过500字');
        }

        // 验证跟进结果
        if (empty($data['result'])) {
            throw new \Exception('跟进结果不能为空');
        }

        if (strlen($data['result']) > 255) {
            throw new \Exception('跟进结果不能超过255字');
        }

        // 实地拜访时验证地址
        if ($data['type'] == 1) {
            if (empty($data['address'])) {
                throw new \Exception('实地拜访时跟进地址不能为空');
            }
            if (strlen($data['address']) > 500) {
                throw new \Exception('跟进地址不能超过500字');
            }
        }

        // 验证图片数量
        if (!empty($data['images']) && is_array($data['images']) && count($data['images']) > 4) {
            throw new \Exception('最多只能上传4张图片');
        }
    }

    /**
     * 获取跟进方式选项
     * @return array
     */
    public function getFollowUpTypes(): array
    {
        return [
            ['value' => 1, 'label' => '实地拜访'],
            ['value' => 2, 'label' => '电话拜访']
        ];
    }

    /**
     * 获取跟进结果选项
     * @param int $type 跟进方式 1实地 2电话
     * @return array
     */
    public function getFollowUpResults(int $type): array
    {
        if ($type == 1) {
            // 实地拜访结果选项
            return [
                ['value' => '有意向建立合作管理', 'label' => '有意向建立合作管理'],
                ['value' => '约定下次见面', 'label' => '约定下次见面'],
                ['value' => '流失', 'label' => '流失']
            ];
        } else {
            // 电话拜访结果选项
            return [
                ['value' => '有意向', 'label' => '有意向'],
                ['value' => '无意向', 'label' => '无意向'],
                ['value' => '需跟进', 'label' => '需跟进']
            ];
        }
    }

    /**
     * 获取可选择的陪同人员列表
     * @param string $keyword 搜索关键词
     * @return array
     */
    public function getPartnerList(string $keyword = ''): array
    {
        $query = SystemUser::where('status', 1);

        if (!empty($keyword)) {
            $query->where('name', 'like', '%' . $keyword . '%');
        }

        return $query->field('id, name, department')
            ->order('name', 'asc')
            ->select()
            ->toArray();
    }
}